#import "Common.h"
#import "DevourerAppDelegate.h"
#import "GameConfig.h"
#import "RootViewController.h"
#import "LayerMainMenu.h"
#import "LayerResult.h"
#import "LayerStore.h"
#import "LayerGame.h"
#import "InvaderBase.h"
#import "DataSL.h"
#import "IAPManager.h"
#import "OpenFeint/OpenFeint.h"

@implementation DevourerAppDelegate

@synthesize window, activityView;

- (void) removeStartupFlicker
{
	//
	// THIS CODE REMOVES THE STARTUP FLICKER
	//
	// Uncomment the following code if you Application only supports landscape mode
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController

//	CC_ENABLE_DEFAULT_GL_STATES();
//	CCDirector *director = [CCDirector sharedDirector];
//	CGSize size = [director winSize];
//	CCSprite *sprite = [CCSprite spriteWithFile:@"Default.png"];
//	sprite.position = ccp(size.width/2, size.height/2);
//	sprite.rotation = -90;
//	[sprite visit];
//	[[director openGLView] swapBuffers];
//	CC_ENABLE_DEFAULT_GL_STATES();
	
#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController	
}
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	// Try to use CADisplayLink director
	// if it fails (SDK < 3.1) use the default director
	if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
		[CCDirector setDirectorType:kCCDirectorTypeDefault];
	
	
	CCDirector *director = [CCDirector sharedDirector];
	
	// Init the View Controller
	viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
	viewController.wantsFullScreenLayout = YES;
	
	//
	// Create the EAGLView manually
	//  1. Create a RGB565 format. Alternative: RGBA8
	//	2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
	//
	//
	EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
								   pixelFormat:kEAGLColorFormatRGB565	// kEAGLColorFormatRGBA8
								   depthFormat:0						// GL_DEPTH_COMPONENT16_OES
						];
	
	// attach the openglView to the director
	[director setOpenGLView:glView];
	
//	// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
//	if( ! [director enableRetinaDisplay:YES] )
//		CCLOG(@"Retina Display Not supported");
	
	//
	// VERY IMPORTANT:
	// If the rotation is going to be controlled by a UIViewController
	// then the device orientation should be "Portrait".
	//
	// IMPORTANT:
	// By default, this template only supports Landscape orientations.
	// Edit the RootViewController.m file to edit the supported orientations.
	//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
	[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
	[director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
#endif
	
	[director setAnimationInterval:1.0/60];
//	[director setDisplayFPS:YES];
	
	if([director enableRetinaDisplay:YES])
		gHDSuffix=@"";
	else
		gHDSuffix=@"-sd";
	
	[glView setMultipleTouchEnabled:YES];	
	// make the OpenGLView a child of the view controller
	[viewController setView:glView];
	
	// make the View Controller a child of the main window
	[window addSubview: viewController.view];
	
	[window makeKeyAndVisible];
	
	activityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
	[activityView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
	[glView addSubview:activityView];
	[activityView release];
	
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

	[self removeStartupFlicker];
	
	[self initGame:true];
}

-(void)initGame:(bool)first
{
	if(first) {
		srand(time(NULL));
		
		[IAPManager sharedManager];
		
		// 读取存盘数据
		gLoadData();
		
		// OpenFient
		NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
								  [NSNumber numberWithInt:UIDeviceOrientationLandscapeLeft],OpenFeintSettingDashboardOrientation,
								  @"Devourer",OpenFeintSettingShortDisplayName,
								  [NSNumber numberWithBool:YES],OpenFeintSettingEnablePushNotifications,
								  [NSNumber numberWithBool:NO],OpenFeintSettingDisableUserGeneratedContent,nil];
		
		OFDelegatesContainer* delegates = [OFDelegatesContainer containerWithOpenFeintDelegate:nil];
		
		[OpenFeint initializeWithProductKey:@"zFRHV65ZalXkxJPcKSTgw"
								  andSecret:@"SN8TCBpnuCKHNhl3Qzcco6RGkX0jbRXZBn0e3ZQIs"
							 andDisplayName:@"Devourer"
								andSettings:settings
							   andDelegates:delegates];
		
		gGCManager = [[GCManager alloc] initWithView:viewController];
		[gGCManager authenticateLocalPlayer];
		
		gCreateInvaders();
		
		//	for(int i=0; i<SOUND_COUNT; i++)
		//		[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:gSoundFile[i]];
		
		[[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:gSettingData.musicOn ? 0.8 : 0];
		[[SimpleAudioEngine sharedEngine] setEffectsVolume:gSettingData.soundOn ? 1 : 0];

		[[CCDirector sharedDirector] runWithScene: [SceneMainMenu node]];
	}		
	else
		[[CCDirector sharedDirector] replaceScene: [SceneMainMenu node]];
	
	[[SimpleAudioEngine sharedEngine] playBackgroundMusic:MUSIC_BG1 loop:true];	
	[activityView stopAnimating];

	// Review
	if(gGlobalData.reviewTimes > 0) {
		gGlobalData.reviewTimes--;
		if(gGlobalData.reviewTimes == 0) {
			gGlobalData.reviewTimes = 10;
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"BtnRate",nil)
															message:NSLocalizedString(@"RateMsg",nil)
														   delegate:self
												  cancelButtonTitle:NSLocalizedString(@"BtnRemind",nil)
												  otherButtonTitles:NSLocalizedString(@"BtnGoto",nil), nil];
			[alert show];
			[alert release];
		}
	}
}

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex == 1) {
		// Rate it
		gGlobalData.reviewTimes = -1;
		gSaveData();
		NSString* str = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=461205872&onlyLatestVersion=false&type=Purple+Software&sortOrding=1";
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
	}
}

- (void)applicationWillResignActive:(UIApplication *)application {
	gSaveData();
	[[CCDirector sharedDirector] pause];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	[[CCDirector sharedDirector] resume];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
	[[CCDirector sharedDirector] purgeCachedData];
}

-(void) applicationDidEnterBackground:(UIApplication*)application {
	[[CCDirector sharedDirector] stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application {
	[self initGame:false];
	[[CCDirector sharedDirector] startAnimation];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	gSaveData();
	CCDirector *director = [CCDirector sharedDirector];
	[[director openGLView] removeFromSuperview];
	[viewController release];
	[window release];
	[director end];	
}

- (void)applicationSignificantTimeChange:(UIApplication *)application {
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void)dealloc {
	[[CCDirector sharedDirector] release];
	[window release];
	[super dealloc];
}

@end
